﻿using Microsoft.AspNetCore.SignalR;
using OA.Infrastructure.SignalR.Abstractions;
using OA.Infrastructure.SignalR.Hubs;
using Quartz;

namespace OA.Infrastructure.Job;

[DisallowConcurrentExecution, PersistJobDataAfterExecution]
internal class SendNotificationWithData : IJob
{
    private readonly IServiceProvider _serviceProvider;

    public string Description { private get; set; } = null!;
    public DateTime TriggedDate { private get; set; }

    public SendNotificationWithData(IServiceProvider sp)
    {
        _serviceProvider = sp;
    }

    public async Task Execute(IJobExecutionContext context)
    {
        var key = context.JobDetail.Key;

        var dataMap = context.JobDetail.JobDataMap;
        var triggerDataMap = context.Trigger.JobDataMap;
        var mergedDataMap = context.MergedJobDataMap;

        var service = _serviceProvider.GetRequiredService<ISignalRService>();

        await service.Factory
            .CreateGenericFactory<NotifyHub>()
            .CreateAllProxy()
            .SendAsync("ReceiveNotification", new MessageRecord<string>
            {
                Sender = "System",
                Data = Description
            }, context.CancellationToken);

        await Console.Error.WriteLineAsync($"实例：{key}, 描述：{Description}");
    }
}